package Servlet;

import DAO.CustomerDAO;
import DAO.DAOFactory;
import javabean.Customer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/Changeinfo")
public class ChangeinfoServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType( "text/html; charset=UTF-8");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        Customer customer = (Customer) request.getSession().getAttribute("loginCustomer");
        CustomerDAO customerDAO = (CustomerDAO) DAOFactory.getCustomerDAOInstance();
        boolean result;
        try {
            customer.setCustomerName(name);
            customer.setCustomerPhone(phone);
            customer.setCustomerAddress(address);
            result = customerDAO.updateCustomer(customer);
            customer = customerDAO.searchCustomer(customer.getCustomerID());
            HttpSession session = request.getSession();
            session.setAttribute("loginCustomer", customer);
            if (result) {
                request.getRequestDispatcher("Personal_Info.jsp").forward(request,response);
            } else {
                response.sendRedirect("updateInfo.jsp");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
